package com.totobox.apps.activity;

import java.io.BufferedInputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.totobox.apps.Const;
import com.totobox.apps.R;
import com.totobox.apps.common.BitmapDownTask;
import com.totobox.apps.common.DBHelper;
import com.totobox.apps.common.FileUtils;
import com.totobox.apps.common.Member;
import com.totobox.apps.common.Util;

public class TotoPhotoViewActivity extends BasicActivity {

	private ImageView photo_img;
	private TextView txt_filename;
	private TextView txt_current;

	public ImageButton btn_bookmark;
	public ImageButton btn_download;

	private ViewFlipper m_viewFlipper;
	private int m_nPreTouchPosX = 0;
	// private final ImageDownloader imageDownloader = new ImageDownloader();

	private int position = 0;
	private int total_position = 0;

	DBHelper mHelper;
	public SQLiteDatabase db;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.my_photo_view);

		// 상단 타이틀 초기화
		super.initTitle();

		// 하단 메뉴 세팅
		super.setFooterMenu(this);

		m_viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
		m_viewFlipper.setOnTouchListener(MyTouchListener);

		position = getIntent().getIntExtra("position", 0);

		photo_img = (ImageView) findViewById(R.id.photo_img);

		btn_bookmark = (ImageButton) findViewById(R.id.btn_bookmark);
		btn_bookmark.setOnClickListener(this);
		btn_download = (ImageButton) findViewById(R.id.btn_download);
		btn_download.setEnabled(Const.isServer);
		

		txt_filename = (TextView) findViewById(R.id.txt_filename);
		txt_current = (TextView) findViewById(R.id.txt_current);

		if (Const.dnQueue != null && !Const.dnQueue.isEmpty()) {

			// 이전에 클릭된 포지션 값
			position = getIntent().getIntExtra("curPosition", 0);

			total_position = Const.dnQueue.size();
			// txt_filename.setText("");
			txt_current.setText(position + " / " + total_position);
		}

		this.PhotoView(position);

		mHelper = new DBHelper(this);
		db = mHelper.getWritableDatabase();

		// 북마크 되어 있는지 체크해서 북마크 버튼 이미지 처리
		Map<String, String> data = Const.dnQueue.get(position);

		boolean isLocation = true;
		if (data.get("vcFilePath") == null)
			isLocation = false;

		String[] bind = { isLocation ? data.get("biFileSeq") : data
				.get("biCursorSeq") };
		Cursor cursor = db.rawQuery("select count(*) count from bookmark where biFileSeq = ?",bind);
		cursor.moveToFirst();

		int dataCount = cursor.getInt(0);
		cursor.close();

		if (dataCount > 0)
			btn_bookmark.setPressed(true);
		else
			btn_bookmark.setPressed(false);
	}

	@Override
	public void onClick(View v) {

		// 이전 액티비티 이동
		if (v == btn_title_left) {
			finish();
		} else if (v == btn_bookmark) {
			this.clickedBookmark();
		} else if (v == btn_download) {
			this.clickedDownload();
		}
	}

	/**
	 * 다운
	 */
	public void clickedDownload() {
		if (Member.tiMemberStatus.equals(254)) {
			super.showText(this, "다운로드 금지 사용자입니다.");
	        return;
	    }

		Map<String,String> data = Const.dnQueue.get(position);
		
		String[] bind = {data.get("biCursorSeq")};
		Cursor cursor = db.rawQuery("select count(*) count from download where biFileSeq = ?", bind);
    	cursor.moveToFirst();
    	
    	int dataCount = cursor.getInt(0);
    	cursor.close();
    	
    	if (!Const.isServer && dataCount > 0) {
    		super.showText(this, "이미 다운로드 받은 사진입니다.");
            return;
        }
    	
	}

	/**
	 * 북마크 클릭
	 */
	public void clickedBookmark() {
		Map<String, String> data = Const.dnQueue.get(position);

		boolean isLocation = true;
		if (data.get("vcFilePath") == null)
			isLocation = false;

				
		String[] bind = {isLocation ? data.get("biFileSeq"):data.get("biCursorSeq")};
		Cursor cursor = db.rawQuery("select count(*) count from bookmark where biFileSeq = ?", bind);
    	cursor.moveToFirst();
    	
    	int dataCount = cursor.getInt(0);
    	cursor.close();
    	
    	try{
    		if (dataCount == 0) {
        		ContentValues values = new ContentValues();
        		values.put("biFileSeq", isLocation ? data.get("biFileSeq"):data.get("biCursorSeq"));
        		values.put("iLocationType", isLocation);
        	    values.put("iFileType", "1");
        	    values.put("vcName", data.get("vcName"));
        	    values.put("vcFileKey", data.get("vcFileKey"));
        	    values.put("iFileSize", data.get("iFileSize"));
        	    values.put("vcFilePlayTime", data.get("vcFilePlayTime"));
        	    values.put("vcThumbNailInfo", isLocation ? data.get("vcFilePath"):data.get("vcThumbNailInfo"));
        	    values.put("vcOriginDown", isLocation ? data.get("vcFilePath"):data.get("vcOriginDown"));
        	    values.put("vcHighStream", isLocation ? data.get("vcFilePath"):data.get("vcHighStream"));
        	    values.put("vcLowStream", isLocation ? data.get("vcFilePath"):data.get("vcLowStream"));
        		db.insert("bookmark", null, values);
        		btn_bookmark.setPressed(true);
        		super.showText(this, "즐겨찾기에 추가 되었습니다.");
        	}
        	else {
    			db.delete("bookmark", "biFileSeq = ?", bind);
    			btn_bookmark.setPressed(false);
    			super.showText(this, "즐겨찾기에서 삭제 되었습니다.");
        	}
    	} catch (SQLException e){
    		super.showText(this, "오류가 발생하였습니다.");
    	}
	}

	// 이미지
	public void PhotoView(int position) {

		Map<String, String> data = Const.dnQueue.get(position);

		txt_filename.setText(FileUtils.getFileName(data.get("vcName")));

		txt_current.setText((position + 1) + " / " + total_position);

		String image_path = Util.trim(data.get("vcOriginDown"));

		BitmapDownTask dnTask = new BitmapDownTask();
		if (image_path.indexOf("/totofun/") > -1) { // sd카드 이미지

			Bitmap photo = Bitmap.createScaledBitmap(dnTask.downloadBitmap(data.get("vcOriginDown")),Const.WIDTH, Const.WIDTH, true);
			photo_img.setImageBitmap(photo);
		} else {
			photo_img.setImageBitmap(ImageFromURL(data.get("vcOriginDown")));
		}
	}

	private void MoveNextView() {
		
		
		if((position+1) < total_position){
			this.position++;
			this.PhotoView(position);
			
			m_viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.appear_from_right));
			m_viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.disappear_to_left));
			m_viewFlipper.showNext();
		}
		else{
			super.showText(this, "마지막 이미지 입니다.");
		}
		
	}

	private void MovewPreviousView() {

		if( (position-1) >= 0){
			this.position--;
			this.PhotoView(position);
			
			m_viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.appear_from_left));
			m_viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.disappear_to_right));
			m_viewFlipper.showPrevious();
		}
		else{
			super.showText(this, "처음 이미지 입니다.");
		}
		
	}

	View.OnTouchListener MyTouchListener = new View.OnTouchListener() {
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				m_nPreTouchPosX = (int) event.getX();
			}

			if (event.getAction() == MotionEvent.ACTION_UP) {
				int nTouchPosX = (int) event.getX();

				if (nTouchPosX < m_nPreTouchPosX) {
					MoveNextView();
				} else if (nTouchPosX > m_nPreTouchPosX) {
					MovewPreviousView();
				}

				m_nPreTouchPosX = nTouchPosX;
			}

			return true;
		}
	};

	private Bitmap ImageFromURL(String strImageURL) 
	{
	    Bitmap imgBitmap = null;
	    
	    try
	    {
	    	URL url = new URL(strImageURL);
	    	URLConnection conn = url.openConnection();
	    	conn.connect();
	    	
	    	int nSize = conn.getContentLength();
	    	BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), nSize);
	    	imgBitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeStream(bis),Const.WIDTH, Const.WIDTH, true);
	    	
	    	bis.close();
	    }
	    catch (Exception e)
	    {
	    	e.printStackTrace();
	    }
	    
	    return imgBitmap;
	}
	
	@Override
	protected void onDestroy() {
		db.close();
		//초기화 
		Const.isServer = false;
		super.onDestroy();

	}
}